import React, { PureComponent } from 'react';
import { PrimaryGhostC } from '../../../comps';
import { Popover, Tree, Button, message } from 'antd';
import { connect } from 'dva';
import _ from 'lodash';
import style from './index.less';

export default class SetColumns extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      selectedKeys: [],
      checkedKeys: [], //
    };
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    const init = JSON.stringify(this.state.checkedKeys);
    const initN = !nextProps.checkedKeys ? '' : JSON.stringify(nextProps.checkedKeys);
    if (init != initN) {
      this.setState({
        checkedKeys: _.cloneDeep(nextProps.checkedKeys),
      });
    }
  }

  handleVisibleChange = (visible) => {
    this.setState({
      visible: visible,
    });
  };

  onSelect = (selectedKeys, info) => {
    this.setState({
      checkedKeys: selectedKeys,
    });
  };

  cancelAction = () => {
    const { checkedKeys } = this.props;
    this.setState({
      visible: false,
      checkedKeys: _.cloneDeep(checkedKeys),
    });
  };

  handleOk = () => {
    const { columns } = this.props;
    if (this.state.checkedKeys.length == 0) {
      message.warning('请至少选择一列');
      return;
    }
    let newColumns = _.cloneDeep(columns);
    newColumns.map((item) => {
      item.display = false;
      this.state.checkedKeys.map((item1) => {
        if (item1 == item.key) {
          item.display = true;
        }
      });
    });
    this.props.changeCols(newColumns, this.state.checkedKeys);
    this.setState({
      visible: false,
    });
  };

  render() {
    const { treeData, disabled } = this.props;
    const content = (
      <div>
        <Tree treeData={treeData} checkable defaultExpandAll checkedKeys={this.state.checkedKeys} onCheck={this.onSelect} />
        <div className='btnArea'>
          <div className='btnCol'>
            <Button onClick={this.cancelAction} className='reset-button ' style={{ marginLeft: '56px' }}>
              取消
            </Button>
            <Button onClick={this.handleOk} className='search-button ' style={{ marginLeft: '11px' }} disabled={disabled}>
              确定
            </Button>
          </div>
        </div>
      </div>
    );

    return (
      <div>
        <Popover
          placement='bottomLeft'
          content={content}
          trigger='click'
          visible={this.state.visible}
          overlayClassName={style.shstyle}
          onVisibleChange={this.handleVisibleChange}
          style={{ height: '317px', width: '240px' }}
        >
          <PrimaryGhostC title='列选择' disabled={disabled} />
        </Popover>
      </div>
    );
  }
}
